# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time
from selenium.webdriver.common.action_chains import ActionChains
import csv
from fake_useragent import UserAgent
from PIL import Image  # 用于打开图片和对图片处理
from aip import AipOcr
import pandas as pd
import os
"""

"""

# 初始化
def init_driver(url):
    chrome_options = Options()
    # chrome_options.add_argument('--headless') # 无头模式
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_experimental_option('excludeSwitches', ['enable-automation']) # 设置开发模式，避免被检测
    chrome_options.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"')
    # driver = webdriver.Chrome(chrome_options=chrome_options) # 已经设置PATH环境变量
    # 未在PATH环境变量中设置，需要设置驱动可执行路径
    driver = webdriver.Chrome(executable_path='D:\\webdriver\\chromedriver.exe', chrome_options=chrome_options)
    driver.maximize_window()  # 窗口最大化
    driver.get(url)
    # html = driver.page_source
    # print(html)
    return driver


# 获取页面url
def get_url(drive, search, save_path):
    # 初始化查询条件
    init_search(search)
    flag = "否"
    # 判断是否有验证码，如果验证码延时40秒
    img_count = 548
    while True:
        try:
            img_element = driver.find_element_by_xpath('//img[@id="ipocaptcha_CaptchaImage"]')
            # # driver.save_screenshot('pictures.png')  # 全屏截图
            # # page_snap_obj = Image.open('pictures.png')
            # # location = img_element.location
            # # size = img_element.size  # 获取验证码的大小参数
            # # left = location['x']
            # # top = location['y']
            # # right = left + size['width']
            # # bottom = top + size['height']
            # # image_obj = page_snap_obj.crop((left, top, right, bottom))  # 按照验证码的长宽，切割验证码
            # # image_obj.save("cut.png")
            # # time.sleep(30)
            # # url = "https://trademarks.ipo.gov.uk/ipo-tmtext?reset"
            # # driver.get(url)
            # driver.save_screenshot('pictures.png')  # 全屏截图
            # page_snap_obj = Image.open('pictures.png')
            # location = {"x":282, "y":500}
            # size = {"height":60, "width":380}  # 获取验证码的大小参数
            # left = location['x']
            # top = location['y']
            # right = left + size['width']
            # bottom = 589 #top + size['height']
            # image_obj = page_snap_obj.crop((left, top, right, bottom))  # 按照验证码的长宽，切割验证码
            # image_obj.save(f"./img/{str(img_count)}.png")
            # img_count += 1
            time.sleep(2)
            # 初始化查询条件
            # init_search(search)
        except:
            try:
                # 未搜索到结果1. 重试 2.未找到
                WebDriverWait(driver, 2).until(
                    EC.presence_of_element_located((By.CLASS_NAME, "error-summary-list")))
                errorMsg = driver.find_element_by_xpath('//ul[@class="error-summary-list"]/li').text
                # 保存结果
                with open(save_path, 'a+', encoding="utf-8-sig", newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([search, flag])
                try:
                    driver.find_element_by_xpath('//a[contains(text(),"New search")]').click()
                except:
                    pass
                return
            except:
                # 搜索到结果
                WebDriverWait(driver, 2).until(
                    EC.presence_of_element_located((By.CLASS_NAME, "search-results")))
                selector = etree.HTML(driver.page_source)
                for s in selector.xpath('//div[@class="search-results"]/div[@class="grid-row"]/div[@class="column-two-thirds"]'):
                    title = "".join(s.xpath('./p[@class="bold-medium"]/a//text()'))
                    # if title.find("EU") == 0 or title.find("WE") == 0 or title.find("WO") == 0:
                    if title.find("EU") == 0:
                        flag = "是"
                        break
                # 保存结果
                with open(save_path, 'a+', encoding="utf-8-sig", newline='') as f:
                    csv_writer = csv.writer(f)
                    csv_writer.writerow([search, flag])
                driver.find_element_by_xpath('//a[contains(text(),"New search")]').click()
                return
                # try:
                #     driver.find_element_by_xpath('//a[contains(@title,"Go to next page")]').click()
                # except:
                #     driver.find_element_by_xpath('//a[contains(text(),"New search")]').click()
                #     return
                # # 保存结果
                # with open(save_path, 'a+', encoding="utf-8-sig", newline='') as f:
                #     csv_writer = csv.writer(f)
                #     csv_writer.writerow([search, flag])

def init_search(search):
    while True:
        try:
            # 设置等待
            WebDriverWait(driver, 5).until(
                EC.presence_of_element_located((By.NAME, "wordSearchPhrase")))
            # 清空search
            driver.find_element_by_name("wordSearchPhrase").clear()
            # 设置搜索条件
            driver.find_element_by_name("wordSearchPhrase").send_keys(search)

            selectTag = Select(driver.find_element_by_name("wordSearchType"))
            selectTag.select_by_index(1)
            time.sleep(0.2)
            selectTag1 = Select(driver.find_element_by_name("legalStatus"))
            selectTag1.select_by_index(1)
            # time.sleep(0.2)
            # selectTag2 = Select(driver.find_element_by_name("pageSize"))
            # selectTag2.select_by_index(4)
            # 查询
            driver.find_element_by_id("button").click()
            return
        except:
            pass


def close_driver(driver):
    driver.quit()

if __name__ == '__main__':
    source_list = []
    target_list = []
    target_value_list = []
    search_list = []
    source_list_count = 0
    target_list_count = 0
    search_list_count = 0

    source_path = "./DZ.xlsx"
    target_path = "./DZ_1.csv"

    line_num = 0
    # source_path文件
    df_s = pd.read_excel(source_path, header=None)
    for index, row in df_s.iterrows():
        source_list.append(str(row[0]).strip())

    source_list_count = len(source_list)

    # 如果有target_path文件
    if os.path.exists(target_path):
        # target_path文件
        df_t = pd.read_csv(target_path, header=None)
        for index, row in df_t.iterrows():
            target_list.append(str(row[0]).strip())
            target_value_list.append(str(row[1]).strip())

        target_list_count = len(target_list)

    # 对比未搜索的关键词，并将结果保存到search_list
    for i in range(0, source_list_count):
        if source_list[i] in target_list:
            pass
        else:
            search_list.append(source_list[i].strip())

    search_list_count = len(search_list)

    url = "https://trademarks.ipo.gov.uk/ipo-tmtext?reset"
    driver = init_driver(url)
    for s in search_list:
        line_num += 1
        print(f"====剩余数量:{search_list_count - line_num}=======完成数量:{line_num}=====关键词:{s}=============")
        get_url(driver, s, target_path)